package com.example.hospitalapp;

import android.os.Bundle;
import android.widget.ListView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

import org.json.JSONArray;
import org.json.JSONObject;

import java.util.ArrayList;

public class AppointmentListActivity extends AppCompatActivity {

    private ListView listViewAppointments;
    private ArrayList<Appointment> appointmentsList;
    private AppointmentAdapter adapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_appointment_list);

        listViewAppointments = findViewById(R.id.listViewAppointments);  // 获取 ListView
        appointmentsList = new ArrayList<>();  // 初始化预约列表

        // 获取传递过来的患者信息
        Patient patient = (Patient) getIntent().getSerializableExtra("patient_info");
        if (patient != null) {
            // 根据病人ID查询所有预约
            queryAppointments(patient.getPatientId());
        }
    }

    // 查询病人的预约
    private void queryAppointments(int patientId) {
        JSONObject params = new JSONObject();
        try {
            params.put("patientId", patientId);  // 传递病人ID查询
        } catch (Exception e) {
            e.printStackTrace();
        }

        ApiClient apiClient = new ApiClient(AppointmentListActivity.this);
        apiClient.postRequest("http://zhsj.autumnclouds.cn/appointment/query", params, new ApiClient.VolleyCallback() {
            @Override
            public void onSuccess(JSONObject response) {
                try {
                    int code = response.getInt("code");
                    if (code == 200) {
                        // 获取预约数据
                        JSONArray appointments = response.getJSONArray("data");
                        appointmentsList.clear();  // 清空现有的预约列表，确保不会重复
                        for (int i = 0; i < appointments.length(); i++) {
                            JSONObject appointmentData = appointments.getJSONObject(i);
                            Appointment appointment = new Appointment(
                                    appointmentData.getInt("appointmentId"),
                                    appointmentData.getString("appointmentTime"),
                                    appointmentData.getString("status"),
                                    appointmentData.getString("paymentStatus"),
                                    appointmentData.getInt("doctorId"),
                                    appointmentData.getInt("patientId"));
                            appointmentsList.add(appointment);
                        }

                        // 使用适配器展示预约数据
                        adapter = new AppointmentAdapter(AppointmentListActivity.this, appointmentsList);
                        listViewAppointments.setAdapter(adapter);

                        // 获取医生信息并填充
                        for (Appointment appointment : appointmentsList) {
                            // 在此确保每次更新医生信息时清除之前的数据，避免缓存错误信息
                            appointment.setDoctorName(null);  // 清空医生姓名
                            appointment.setSpecialty(null);   // 清空科室信息
                            queryDoctorInfo(appointment.getDoctorId(), appointment);
                        }
                    } else {
                        Toast.makeText(AppointmentListActivity.this, "未查询到预约信息", Toast.LENGTH_SHORT).show();
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    Toast.makeText(AppointmentListActivity.this, "查询预约失败", Toast.LENGTH_SHORT).show();
                }
            }
            @Override
            public void onFailure(String error) {
                Toast.makeText(AppointmentListActivity.this, "查询预约失败", Toast.LENGTH_SHORT).show();
            }
        });
    }

    // 查询医生信息并填充科室信息
    private void queryDoctorInfo(int doctorId, Appointment appointment) {
        JSONObject params = new JSONObject();
        try {
            params.put("doctorId", doctorId);  // 传递医生ID查询
        } catch (Exception e) {
            e.printStackTrace();
        }

        ApiClient apiClient = new ApiClient(AppointmentListActivity.this);
        apiClient.postRequest("http://zhsj.autumnclouds.cn/doctor/query", params, new ApiClient.VolleyCallback() {
            @Override
            public void onSuccess(JSONObject response) {
                try {
                    int code = response.getInt("code");
                    if (code == 200) {
                        JSONArray data = response.getJSONArray("data");
                        boolean doctorFound = false;

                        // 遍历医生列表，找到匹配的 doctorId
                        for (int i = 0; i < data.length(); i++) {
                            JSONObject doctorData = data.getJSONObject(i);
                            int currentDoctorId = doctorData.getInt("doctorId");

                            // 如果 doctorId 匹配，则更新医生信息
                            if (currentDoctorId == doctorId) {
                                String doctorName = doctorData.getString("name");
                                String specialty = doctorData.getString("specialty"); // 获取医生的科室

                                // 更新当前预约的医生信息
                                appointment.setDoctorName(doctorName);  // 设置医生姓名
                                appointment.setSpecialty(specialty);    // 设置科室

                                doctorFound = true;
                                break;  // 找到匹配的医生，跳出循环
                            }
                        }

                        // 如果找到了对应的医生，刷新适配器
                        if (doctorFound) {
                            adapter.notifyDataSetChanged();  // 刷新列表，确保医生信息被更新
                        } else {
                            Toast.makeText(AppointmentListActivity.this, "未找到该医生", Toast.LENGTH_SHORT).show();
                        }
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    Toast.makeText(AppointmentListActivity.this, "获取医生信息失败", Toast.LENGTH_SHORT).show();
                }
            }
            @Override
            public void onFailure(String error) {
                Toast.makeText(AppointmentListActivity.this, "查询预约失败", Toast.LENGTH_SHORT).show();
            }
        });
    }
}
